import express from 'express'
import initUpload from '../../util/upload.js'
import * as article from '../../controllers/articles.js'

const upload = initUpload();

const router = express.Router();

router.post("/publish", upload.single("cover"), async (req, res) => {
    console.log(req.body);
    console.log(req.file);
    console.log("http://127.0.0.1:8080/upload/" + req.file.filename);


    res.send({
        code: 200,
        msg: "文章发布成功"
    });
})

//12.根据id获取文章信息

router.get("/search", async (req, res) => {
    let id = req.query.id ?? "";
    if (id == "") {
        res.send({
            code: 400,
            msg: "文章ID参数错误"
        });
        return;
    }

    let data = await article.selectArticleById(id);
    res.send({
        code: 200,
        msg: "查询成功",
        data
    })
})

//13.删除文章
router.post("/delete", async (req, res) => {
    let id = req.body.id ?? "";
    if (id == "") {
        res.send({
            code: 400,
            msg: "文章ID参数错误"
        });
        return;
    }
    await article.deleteArticleById(id);
    res.send({
        code: 200,
        msg: "删除成功",
    })
})


//13.文章编辑
router.post("/edit", async (req, res) => {

    let id = req.body.id ?? "";
    let title = req.body.title ?? "";
    let cover = req.body.cover ?? "";
    let categoryId = req.body.categoryId ?? "";
    let date = req.body.date ?? "";
    let content = req.body.content ?? "";
    let state = req.body.state ?? "0";

    // 必要参数验证
    if (id == "" || title == "" || categoryId == "" || date == "" || content == "") {
        res.send({
            code: 400,
            msg: "缺少必要参数"
        });
        return;
    }

    try {
        let data = await article.updateArticleById(id, title, cover, categoryId, date, content, state);
        res.send({
            code: 200,
            msg: "修改成功",
            data
        });
    } catch (error) {
        console.error("编辑文章失败:", error);
        res.send({
            code: 500,
            msg: "服务器内部错误"
        });
    }
    let data = await article.updateArticleById(id, title, cover, categoryId, date, content, state);
    res.send({
        code: 200,
        msg: "修改成功",
        data
    });
});


export default router;